/**
 * 表单注册页面，一些常用的注册需要用到的组件
 * 用户名，密码，性别，年龄，状态，爱好，婚状，生日，联系地址，时间，头像
 * 输入框，单选，数字选择器，select选择器，select多选，switch，时间选择器，多行文本，上传组件
 */
import { Button, Card, Checkbox, DatePicker, Form, Icon, Input, InputNumber, message, Radio, Select, Switch, TimePicker, Upload } from 'antd'
import moment from 'moment';
import React, { Component } from 'react'
import '../form.less'

import { IProps, IState } from "./types";

const FormItem = Form.Item; // 表单item
const RadioGroup = Radio.Group // 单选
const { Option } = Select; // 选择子项
const { TextArea } = Input // 多行文本

@(Form.create() as any)
export default class FormRegister extends Component<IProps, IState> {

  public state: IState
  constructor(props: Readonly<IProps>) {
    super(props);
    this.state = {
      loading:false
    };
  }

  /**
   * 点击登录按钮出发的函数
   * @param {object} e 点击元素自身属性
   */
  public handleSubmit = (e:any) => {
    // 这个我不知道有啥用
    e.preventDefault();

    // 1. 不使用验证规则，直接获取数据
    // let userInfo = this.props.form.getFieldsValue();
    // console.log(JSON.stringify(userInfo))
    // message.success(`${userInfo.userName} 恭喜你，您通过本次表单组件学习，当前密码为：${userInfo.userPwd}`)

    // 2. 使用验证规则，需要验证都通过
    this.props.form.validateFields((err:any, values:{password:string}) => {
      if (!err) {
        console.log('Received values of form: ', values);
        message.success('恭喜您登录成功,密码为:' + values.password);
      }
    });
  }

  /**
   * 解析图片，官网取下来的
   * @param {Url} img
   * @param {function} callback 回调
   */
  public getBase64 = (img:any, callback:any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  /**
   * 上传文件改变时的状态
   */
  public handleChange = (info:any) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, (imageUrl:string) => this.setState({
        userImg: imageUrl,
        loading: false,
      }));
    }
  }

  public normFile = (e:any) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  public render() {
    const { getFieldDecorator } = this.props.form;

    // 控制表单内部分布1
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      }
    }
    // 控制表单内部分布2
    const offsetLayout = {
      wrapperCol: {
        xs: 24,
        sm: {
          span: 12,
          offset: 4
        }
      }
    }
    // 定义最小最多多少行
    const rowObject = {
      minRows: 4, maxRows: 6
    }

    // 规则定义
    const config = {
      rules: [{ type: 'object', required: true, message: 'Please select time!' }],
    };

    return (
      <div>
        <Card>
          {/* 全局调用布局 */ }
          <Form { ...formItemLayout } layout="horizontal" onSubmit={ this.handleSubmit }>
            <FormItem label="用户名">
              {
                getFieldDecorator('userName', {
                  initialValue: '',
                  rules: [
                    {
                      required: true,
                      message: '用户名不能为空'
                    }
                  ]
                })(
                  <Input
                    prefix={ <Icon type="user" style={ { color: 'rgba(0,0,0,.25)' } } /> }
                    placeholder="请输入用户名"
                  />
                )
              }
            </FormItem>
            <FormItem label="密 码">
              { getFieldDecorator('password', {
                initialValue: '',
                rules: [{ required: true, message: 'Please input your Password!' }],
              })(
                <Input
                  prefix={ <Icon type="lock" style={ { color: 'rgba(0,0,0,.25)' } } /> }
                  type="password"
                  placeholder="请输入密码"
                />,
              ) }
            </FormItem>
            <FormItem label="性别">
              { getFieldDecorator('sex', {
                initialValue: '1'
              })(
                <RadioGroup>
                  <Radio value="1">男</Radio>
                  <Radio value="2">女</Radio>
                </RadioGroup>
              ) }
            </FormItem>
            <FormItem label="年龄">
              { getFieldDecorator('input-number', { initialValue: 18 })(<InputNumber min={ 1 } max={ 200 } />) }
            </FormItem>
            <FormItem label="当前状态">
              { getFieldDecorator('state', { initialValue: '2' })(
                <Select>
                  <Option value="1">a</Option>
                  <Option value="2">b</Option>
                  <Option value="3">c</Option>
                  <Option value="4">d</Option>
                  <Option value="5">e</Option>
                </Select>
              ) }
            </FormItem>
            <FormItem label="爱好">
              { getFieldDecorator('state', { initialValue: ['2', '6'] })(
                <Select mode="multiple">
                  <Option value="1">游泳</Option>
                  <Option value="2">打篮球</Option>
                  <Option value="3">踢足球</Option>
                  <Option value="4">跑步</Option>
                  <Option value="5">爬山</Option>
                  <Option value="6">骑行</Option>
                  <Option value="7">桌球</Option>
                  <Option value="8">麦霸</Option>
                </Select>
              ) }
            </FormItem>
            <FormItem label="是否已婚">
              {
                getFieldDecorator('isMarried', {
                  valuePropName: 'checked',
                  initialValue: false
                })(
                  <Switch />
                )
              }
            </FormItem>
            <FormItem label="生日">
              { getFieldDecorator('birthday', { initialValue: moment('2019-08-08'), rules: [{ type: 'object', required: true, message: 'Please select time!' }] })(<DatePicker showTime={true} format="YYYY-MM-DD HH:mm:ss" />) }
            </FormItem>
            <FormItem label="联系地址">
              {
                getFieldDecorator('address', {
                  initialValue: '北京市海淀区奥林匹克公园'
                })(
                  <TextArea
                    autosize={ rowObject }
                  />
                )
              }
            </FormItem>
            <FormItem label="早起时间">
              { getFieldDecorator('time', config)(<TimePicker />) }
            </FormItem>
            <FormItem label="头像上传">
              { getFieldDecorator('userImg', {
                valuePropName: 'fileList',
                getValueFromEvent: this.normFile,
              })(
                <Upload
                  listType="picture-card"
                  showUploadList={ false }
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  onChange={ this.handleChange }
                >
                  { this.state.userImg ? <img src={ this.state.userImg } alt="" /> : <Icon type="plus" /> }
                </Upload>
              ) }
            </FormItem>
            <FormItem  { ...offsetLayout }>
              {
                getFieldDecorator('userImg')(
                  <Checkbox>我已阅读过<a href="https://yhf7.top">慕课协议</a></Checkbox>
                )
              }
            </FormItem>
            <FormItem { ...offsetLayout }>
              <Button type="primary" htmlType="submit">注册</Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    )
  }
}

// export default Form.create()(FormRegister)